<?php
namespace api\modules\v1\models\coin;

use api\modules\common\models\User;
use api\modules\v1\models\Common;
use common\models\CacheKeys;
use common\models\Email;
use common\models\Functions;
use common\models\Patterns;
use common\models\pay\Alipay;
use common\models\Status;
use common\models\userFund\UserMoneyLog;
use common\models\userLevel\UserLevelLog;
use common\services\pay\iosPay\IosPay;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * Class GoodsSpec
 * @package api\modules\v1\models
 */
class CoinRechargeOrder extends \common\models\coin\CoinRechargeOrder
{


    /**
     * 购买金币订单
     * @return array
     */
    public function createOrder() {
        $trans = Yii::$app->getDb()->beginTransaction();
        $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
        $redis = Yii::$app->redis;
        $redisKey = "COIN_RECHARGE_ORDER_" . $userInfo['id'];
        try {
            $exists = $redis->get($redisKey);
            if($exists){
                throw new Exception('速度太快，请稍后尝试！');
            }

            $post = Yii::$app->request->post();
            $coinId = (int) $post['coin_id'];
            $payWay = Yii::$app->request->post('pay_way',0); //1-余额  2-银行卡购买 3-内购
            $receiptData = Yii::$app->request->post('receipt_data',""); //ios返回的数据

            if (empty($coinId)) {
                throw new Exception('购买信息错误');
            }
            $coinInfo = CoinRechargeSetting::getOneInfoById($coinId);
            if (empty($coinInfo)) {
                throw new Exception('购买信息错误');
            }

            if (!$payWay) {
                throw new Exception('请选择付款方式');
            }

            if (!in_array($payWay,array_keys(Status::PAY_WAY_MAP))) {
                throw new Exception('支付方式不合法');
            }


            $orderNumber = $this->_createOrderNumber();


            $date = date("Y-m-d H:i:s");

            $order['order_number'] = $orderNumber;
            $order['user_id'] = $userInfo['id'];
            $order['setting_id'] = $coinId;
            $order['money'] = (double) $coinInfo['money'];
            $order['coin'] = (double) $coinInfo['coin'];
            $order['create_time'] = $date;
            $order['status'] = Status::COIN_RECHARGE_ORDER_STATUS_WAITING_APY;
            $order['pay_way'] = $payWay;
            $res = static::insertData($order);
            if ($res === false) {
                throw new Exception('系统错误，请稍后再试');
            }

            // 余额支付
            if ($payWay == Status::PAY_WAY_MONEY && $order['money'] > 0) {
                $this->balancePay($orderNumber, $order['money'], $date);
                $trans->commit();
                return Functions::formatRestAPI(0, '充值成功！');
            }

            // 银行卡支付
            if ($payWay == Status::PAY_WAY_BANK && $order['money'] > 0) {
                throw new Exception('暂未开通');

                $trans->commit();
                return Functions::formatRestAPI(0, '创建成功，请尽快支付');
            }

            // 内购支付
            if ($payWay == Status::PAY_WAY_IOS && $order['money'] > 0) {

                if (empty($receiptData)) {
                    throw new Exception("苹果支付参数有误！");
                }

                $this->iosPay($orderNumber, $order['buy_money'], $date, $receiptData);

                $trans->commit();
                return Functions::formatRestAPI(0, '创建成功，请尽快支付');
            }

            //支付宝支付
            if ($payWay == Status::PAY_WAY_ALIPAY && $order['money'] > 0) {
                $aliPayModel = new Alipay();

                $resAlipay = $aliPayModel->payCoin($orderNumber, 'app');

                if (isset($resAlipay['status']) && $resAlipay['status'] === false) {
                    throw new Exception($res['message']);
                }
                $trans->commit();
                return Functions::formatRestAPI(0, '创建成功，请尽快支付', $resAlipay);
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '创建成功，请尽快支付');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        } finally {
            $redis->del($redisKey);
        }
    }

    /**
     * 订单列表
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getList($page = 1, $size = 50) {
        try {
            $page = (int) $page;
            $size = (int) $size;
            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
            $where = [
                'user_id' => $userInfo['id'],
                'status' => Status::LEVEL_ORDER_STATUS_DONE
            ];

            $count = static::getCountByWhere($where);
            $data = static::setPaginationForApi($page);

            $offset = ($page - 1) * $size;
            $list = static::getObjectByWhere($where, ['*'], 'status ASC, pay_time DESC', $offset, $size)
                ->with(['level'])->asArray()->all();

            $result = [];
            foreach ($list as $k => $v) {
                $singleLevelInfo = ArrayHelper::getValue($v,'level',[]);
                $result[] = [
                    'id' => (int) $v['id'],
                    'order_number' => $v['order_number'],
                    'buy_money' => floatval($v['buy_money']),
                    'create_date' => date('Y-m-d',strtotime($v['create_time'])),
                    'create_time' => date('H:i:s',strtotime($v['create_time'])),
                    'pay_time' => $v['pay_time'] ?: '',
                    'status' => $v['status'],
                    'status_name' => Status::LEVEL_ORDER_STATUS_MAP[$v['status']],
                    'buy_level' => $singleLevelInfo['name'] ?? '',
                ];
            }
            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
